/**
 * 缓存管理工具
 * 提供统一的缓存清除机制，支持组织切换时清除相关缓存
 */

import { API_CONFIG } from '@/api/config.js'
import productCache from '@/utils/productCache.js'
import cartCache from '@/utils/cartCache.js'
import couponCache from '@/utils/couponCache.js'

const CACHE_KEYS = {
  // 轮播图缓存
  BANNER: 'banner_cache',
  // 公告缓存
  ANNOUNCEMENT: 'announcement_cache',
  // 订单缓存
  ORDER: 'order_cache',
  // 分类缓存
  CATEGORY: 'category_cache',
  // 品牌缓存
  BRAND: 'brand_cache',
  // 地址缓存
  ADDRESS: 'address_cache',
  // 评论缓存
  COMMENT: 'comment_cache',
  // 优惠券缓存
  COUPON: 'coupon_cache'
}

export default {
  /**
   * 清除指定组织的所有缓存
   * @param {string} orgId 组织ID
   */
  clearOrgCache(orgId = API_CONFIG.ORG_ID) {
    console.log(`开始清除组织 ${orgId} 的所有缓存`)
    
    // 清除商品相关缓存
    productCache.clearAllProductCache(orgId)
    
    // 清除优惠券缓存（需要用户ID，这里清除所有用户的优惠券缓存）
    couponCache.clearAllCouponCacheForOrg(orgId)
    
    // 清除其他带组织ID的缓存
    const orgCacheKeys = [
      `${CACHE_KEYS.BANNER}_org_${orgId}`,
      `${CACHE_KEYS.ANNOUNCEMENT}_org_${orgId}`,
      `${CACHE_KEYS.ORDER}_org_${orgId}`,
      `${CACHE_KEYS.CATEGORY}_org_${orgId}`,
      `${CACHE_KEYS.BRAND}_org_${orgId}`,
      `${CACHE_KEYS.ADDRESS}_org_${orgId}`,
      `${CACHE_KEYS.COMMENT}_org_${orgId}`,
      `product_categories_tree_cache_${orgId}`
    ]
    
    orgCacheKeys.forEach(key => {
      uni.removeStorageSync(key)
      console.log(`已清除缓存: ${key}`)
    })
    
    console.log(`组织 ${orgId} 的所有缓存已清除`)
  },
  
  /**
   * 清除所有组织的缓存
   */
  clearAllCache() {
    try {
      console.log('开始清除所有缓存')
      
      // 清除所有以组织相关前缀开头的缓存
      const keysToRemove = []
      
      // 获取所有存储的键
      const storageInfo = uni.getStorageInfoSync()
      const keys = storageInfo.keys || []
      
      // 遍历所有存储的键
      keys.forEach(key => {
        // 清除组织相关的缓存
        if (key.includes('_cache') || 
            key.includes('product_') || 
            key.includes('category_') ||
            key.includes('cart_') ||
            key.includes('order_') ||
            key.includes('comment_') ||
            key.includes('notice_')) {
          keysToRemove.push(key)
        }
      })
      
      // 批量删除
      keysToRemove.forEach(key => {
        uni.removeStorageSync(key)
      })
      
      console.log('已清除所有组织相关缓存:', keysToRemove)
    } catch (error) {
      console.error('清除缓存失败:', error)
    }
  },
  
  /**
   * 判断是否为缓存键
   * @param {string} key 存储键
   * @returns {boolean}
   */
  isCacheKey(key) {
    const cachePatterns = [
      'products_',
      'global_products_cache',
      'user_cart_cache',
      'banner_cache',
      'announcement_cache',
      'order_cache',
      'category_cache',
      'brand_cache',
      'address_cache',
      'comment_cache',
      'product_categories_tree_cache',
      'comment_detail_'
    ]
    
    return cachePatterns.some(pattern => key.includes(pattern))
  },
  
  /**
   * 清除轮播图缓存
   * @param {string} orgId 组织ID
   */
  clearBannerCache(orgId = API_CONFIG.ORG_ID) {
    const cacheKey = `${CACHE_KEYS.BANNER}_org_${orgId}`
    uni.removeStorageSync(cacheKey)
    console.log(`已清除轮播图缓存: ${cacheKey}`)
  },
  
  /**
   * 清除公告缓存
   * @param {string} orgId 组织ID
   */
  clearAnnouncementCache(orgId = API_CONFIG.ORG_ID) {
    const cacheKey = `${CACHE_KEYS.ANNOUNCEMENT}_org_${orgId}`
    uni.removeStorageSync(cacheKey)
    console.log(`已清除公告缓存: ${cacheKey}`)
  },
  
  /**
   * 清除订单缓存
   * @param {string} orgId 组织ID
   */
  clearOrderCache(orgId = API_CONFIG.ORG_ID) {
    const cacheKey = `${CACHE_KEYS.ORDER}_org_${orgId}`
    uni.removeStorageSync(cacheKey)
    console.log(`已清除订单缓存: ${cacheKey}`)
  },
  
  /**
   * 获取缓存状态信息
   * @param {string} orgId 组织ID
   * @returns {object} 缓存状态
   */
  getCacheStatus(orgId = API_CONFIG.ORG_ID) {
    const status = {
      orgId: orgId,
      products: productCache.getCacheStatus(orgId),
      caches: {}
    }
    
    // 检查其他缓存状态
    Object.entries(CACHE_KEYS).forEach(([name, key]) => {
      const cacheKey = `${key}_org_${orgId}`
      const cacheData = uni.getStorageSync(cacheKey)
      status.caches[name.toLowerCase()] = {
        exists: !!cacheData,
        timestamp: cacheData ? new Date(cacheData.timestamp).toLocaleString() : null
      }
    })
    
    return status
  }
}